import router from '@/router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const service = axios.create({
    baseURL: '/admin-api',
    timeout: 50000
})

service.interceptors.request.use(
    config => {
        const token = localStorage.getItem('sa-token');
        if( token ){
            config.headers['sa-token'] = token;
        }else{
            router.push('/login');
        }
        return config;
    },
    error => {
        Promise.reject(error);
    }
)

service.interceptors.response.use(
    response => {
        const res = response;
        if(res.data.code != 200 ){
            if( res.data.code == 403){
                ElMessage({
                    message: '登录失效，请重新登录',
                    type: 'error',
                    duration: 2000
                })
                router.push('/login');
            }else if(res.data.code == 201){
                ElMessage({
                    message: res.data.msg ,
                    type: 'warning',
                })
            }else{
                ElMessage({
                    message: res.data.msg ,
                    type: 'error',
                    duration: 2000
                })
            }
            return Promise.reject(res.data.msg ? res.data.msg : 'error:102')
        }else{
            return res;
        }
    },
    error => {
        ElMessage({
            message: error.message ,
            type: 'error',
            duration: 2000
        });
        Promise.reject(error);
    }
)

export default service